//
//  AvatarView.m
//  CandyCrushClone
//
//  Created by Petar on 4/23/15.
//  Copyright (c) 2015 Nestorov Engineering. All rights reserved.
//

#import "AvatarView.h"
#import <QuartzCore/QuartzCore.h>

static CGFloat lineWidth = 6.0;
static CGFloat animationDuration = 1.0;

@interface AvatarView ()

@property (nonatomic, assign) BOOL isAnimatedToSquare;

@end

@implementation AvatarView
{
    CALayer *_photoLayer;
    CAShapeLayer *_circleLayer;
    CAShapeLayer *_maskLayer;
    UILabel *_label;
}


- (void)didMoveToSuperview
{
    
    [super didMoveToSuperview];
    
    _photoLayer = [CALayer layer];
    _circleLayer = [CAShapeLayer layer];
    _maskLayer = [CAShapeLayer layer];
    _isAnimatedToSquare = NO;
    
    self.backgroundColor = [UIColor clearColor];
    
    //draw the circle
    _circleLayer.path = [UIBezierPath bezierPathWithOvalInRect:self.bounds].CGPath;
    _circleLayer.strokeColor = [UIColor greenColor].CGColor;
    _circleLayer.lineWidth = lineWidth;
    _circleLayer.fillColor = [UIColor clearColor].CGColor;
    [self.layer addSublayer:_circleLayer];
    
    //add the initial image of the avatar view
    UIImage *blankImage = [UIImage imageNamed:@"waitingOpponentAvatar"];
    [_photoLayer setContents: (__bridge id)blankImage.CGImage];
    _photoLayer.frame = CGRectMake( (self.bounds.size.width - blankImage.size.width + lineWidth)/2,
                                   (self.bounds.size.height - blankImage.size.height - lineWidth)/2,
                                   blankImage.size.width,
                                   blankImage.size.height);
    
    [self.layer addSublayer:_photoLayer];
    
    //mask layer
    _maskLayer.path = _circleLayer.path;
    _maskLayer.position = CGPointMake(0, 10);
    _photoLayer.mask = _maskLayer;
    
    //add label
    _label = [[UILabel alloc] initWithFrame:CGRectMake(-10, self.bounds.size.height + 10, self.bounds.size.width + 20, 24)];
    [_label setFont:[UIFont fontWithName:@"GillSans-BoldItalic" size:21.0]];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.textColor = [UIColor blackColor];
    _label.adjustsFontSizeToFitWidth = YES;
    
    [self addSubview:_label];
    
}


- (void)setName:(NSString *)name withColor:(UIColor *)textColor
{
    
    _name = name;
    
    _label.alpha = 0.3;
    [_label setText:name];
    _label.textColor = textColor;
    
    [UIView animateWithDuration:1 animations:^{
        _label.alpha = 1;
    }];
    
}


- (void)setImage:(UIImage *)image forLocalPlayer:(BOOL)isForLocalPlayer
{
    
    _image = image;
    
    [_photoLayer setContents: (__bridge id)_image.CGImage];
    
    // Flip image for otherPlayer
    if ( isForLocalPlayer == NO ) {
        _photoLayer.transform = CATransform3DMakeScale(-1, 1, 1);
    }
    
}


- (void)setCircleLayerStrokeColor:(UIColor *)strokeColor andFillColor:(UIColor *)fillColor
{
    
    [_circleLayer setStrokeColor:strokeColor.CGColor];
    [_circleLayer setFillColor:fillColor.CGColor];
    
}


- (void)bounceOffPoint:(CGPoint)bouncePoint morphSize:(CGSize)morphSize
{
    
    CGPoint originalCenter = self.center;
    
    __weak AvatarView *weakSelf = self;
    
    [UIView animateWithDuration:animationDuration delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:0 options:0 animations:^{
        
        weakSelf.center = bouncePoint;
        
    } completion:^(BOOL finished) {
        
        if ( weakSelf.shouldTransitionToFinishedState == YES ) {
            
            [weakSelf animateToSquare];
            weakSelf.isAnimatedToSquare = YES;
            
        }
        
        [UIView animateWithDuration:animationDuration delay:0 usingSpringWithDamping:0.9 initialSpringVelocity:10 options:0 animations:^{
            
            weakSelf.center = originalCenter;
            
        } completion:^(BOOL finished) {
            
            if ( weakSelf.shouldTransitionToFinishedState == YES ) {
                
                if ( weakSelf.isAnimatedToSquare == NO ) {
                    [weakSelf animateToSquare];
                }
                
            } else {
                
                [weakSelf delayAfter:0.1 completion:^{
                    [weakSelf bounceOffPoint:bouncePoint morphSize:morphSize];
                }];
                
            }
            
        }];
        
    }];
    
    CGRect morphFrame = (originalCenter.x > bouncePoint.x) ?
    CGRectMake(0, self.bounds.size.height - morphSize.height, morphSize.width, morphSize.height) :
    CGRectMake(self.bounds.size.width - morphSize.width,self.bounds.size.height - morphSize.height , morphSize.width, morphSize.height);
    
    CABasicAnimation *morphAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    morphAnimation.duration = animationDuration;
    morphAnimation.toValue = (__bridge id)([UIBezierPath bezierPathWithOvalInRect:morphFrame].CGPath);
    morphAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    [_circleLayer addAnimation:morphAnimation forKey:nil];
    [_maskLayer addAnimation:morphAnimation forKey:nil];
    
}


- (void)animateToSquare
{
    
    CABasicAnimation *morphAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    morphAnimation.duration = 0.5;
    morphAnimation.fromValue = (__bridge id)(_circleLayer.path);
    morphAnimation.toValue = (__bridge id)([UIBezierPath bezierPathWithRect:self.bounds].CGPath);
    morphAnimation.removedOnCompletion = NO;
    morphAnimation.fillMode = kCAFillModeBoth;
    morphAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    //add morphing to both the shape and the image mask
    [_circleLayer addAnimation:morphAnimation forKey:nil];
    [_maskLayer addAnimation:morphAnimation forKey:nil];
    
}


//
// Util delay function
//
- (void)delayAfter:(CGFloat)seconds completion:(void (^)())completion
{
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, seconds * NSEC_PER_SEC);
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^{
        completion();
    });
    
}


@end
